package edu.sctu.jsoup.service;


import edu.sctu.jsoup.entity.AllBbsEntity;
import edu.sctu.jsoup.entity.EveryForumPostEntity;
import edu.sctu.jsoup.repo.AllBbsRepo;
import edu.sctu.jsoup.repo.EveryForumPostRepo;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Service
public class EveryForumPostService {

    @Autowired
    private AllBbsRepo allBbsRepo;

    @Autowired
    private EveryForumPostRepo everyForumPostRepo;

    public void run() {

        List<AllBbsEntity> allBbsEntities = allBbsRepo.findAll();

        Document document;
        EveryForumPostEntity everyForumPostEntity = new EveryForumPostEntity();

        for (int i = 0; i < allBbsEntities.size(); i++) {
            document = Jsoup.parse(allBbsEntities.get(i).getHtml_content());
            Elements all_dl = document.select("div#subcontent").select("dl.list_dl");

            //第二个dl开始才是帖子
            for (int j = 1; j < all_dl.size(); j++) {

                everyForumPostEntity.setBbsTitle(
                        allBbsEntities.get(i).getTitle()
                );

                everyForumPostEntity.setTitle(
                        all_dl.get(j).select("dt").first()
                                .select("a").first().text()
                );

                everyForumPostEntity.setUrl(
                        all_dl.get(j).select("dt").first()
                                .select("a").first().attr("href")
                );


                /*
                * 待解决问题：.save方法ID不自增，始终只有一条记录
                * */
                System.out.println(
                        everyForumPostEntity.getBbsTitle()+"|"
                                + everyForumPostEntity.getTitle()+"|"
                                + everyForumPostEntity.getUrl());
//                everyForumPostRepo.save(everyForumPostEntity);
            }
        }

    }
}

